package com.uenpay.util.net.retrofit;


import com.socks.library.KLog;
import com.uenpay.util.crypt.AES;
import com.uenpay.util.crypt.CryptUtils;
import com.uenpay.util.net.http.HttpParam;

import org.simpleframework.xml.core.Persister;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;

/**
 * Created by liulou on 2016/5/16.
 * desc:
 */
public class UenConverterFactory extends Converter.Factory {
    private static final MediaType MEDIA_TYPE = MediaType.parse("text/plain");

    @Override
    public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
        if (String.class.equals(type)) {
            return new Converter<String, RequestBody>() {
                @Override
                public RequestBody convert(String value) throws IOException {
                    return RequestBody.create(MEDIA_TYPE, value);
                }
            };
        }
        return null;
    }

    @Override
    public Converter<?, String> stringConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        return super.stringConverter(type, annotations, retrofit);
    }

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(final Type type, Annotation[] annotations, Retrofit retrofit) {
        /**
         * 当返回结果类型为String时使用此Converter
         */
        if (String.class.equals(type)) {
            return new Converter<ResponseBody, String>() {
                @Override
                public String convert(ResponseBody value) throws IOException {
                    String result = AES.decryptString(value.string(), CryptUtils.encryptToMD5(HttpParam.AES_Password));
                    KLog.d("responseBodyConverter  result="+result);
                    return result;
                }
            };
        }
        /**
         * 当请求参数时含有TypeXml的注解时使用UenXmlResponseBodyConverter
         * 先将结果解密然后转换成实体类
         */
        for (Annotation annotation : annotations) {
            if (annotation instanceof TypeXml) {
                final Class<?> cls = (Class<?>) type;
                return new UenXmlResponseBodyConverter<>(cls, new Persister(), false);
            }
        }

        return null;
    }

}
